﻿using Agriculture.Api.Write.AllError;
using Agriculture.Api.Write.Common;
using Agriculture.Api.Write.Files;
using Agriculture.Infrastructure;
using Agriculture.Infrastructure.Impement;
using Agriculture.Infrastructure.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NLog.Web;
using System.Reflection;
using System.Text;

namespace Agriculture.Api.Write.Extensions
{
    /// <summary>
    /// 扩展方法 静态类 静态方法 this关键字
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //注册全局异常处理
            builder.Services.AddControllers(x => x.Filters.Add<GloabIExcptionfilter>());

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "Agriculture.Api.Read.xml", true));
            //注册上下文 开发环境下启用SQL日志记录
            builder.Services.AddDbContext<MyDbContext>(x =>
            {
                x.UseMySql(builder.Configuration.GetConnectionString("db"), new MySqlServerVersion("5.7"), options =>
                {
                    // 配置连接池和并发查询选项
                    options.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                });
                // 启用服务提供程序缓存
                x.EnableServiceProviderCaching();
                // 启用敏感数据日志记录（仅在开发环境）
                if (builder.Environment.IsDevelopment())
                {
                    x.EnableSensitiveDataLogging();
                    x.LogTo(Console.WriteLine, LogLevel.Information);
                }
            });
            ////注册http获取请求上下文
            //builder.Services.AddHttpContextAccessor();
            //builder.Services.AddScoped<IIdentivyService, IdentivyService>();
            //JWT
            var jwtSettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
            //授权认证（使用JWT）
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SigningKey);
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = jwtSettings.Issuer,

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = jwtSettings.Audience,

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });

            // 添加授权服务
            builder.Services.AddAuthorization();

            // 配置Swagger
            builder.Services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[]
                        {

                        }
                    }
                });
            });
            //注册consul
            //builder.Configuration.Register();
            //注册中介者
            builder.Services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //配置Base模块
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //配置AutoMapper
            builder.Services.AddAutoMapper(typeof(MapperProfiles));
            //配置日志
            builder.Host.UseNLog();

            return builder;
        }
    }
}
